package org.jxf.gps.jt808;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jxf.gps.jt808.message.Message;
import org.jxf.gps.jt808.server.GpsServer;

import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Model;

public class OnlineCheckPlugin implements IPlugin {
	private Logger logger = Logger.getLogger(OnlineCheckPlugin.class);

	public boolean start() {
		logger.info("OnlineCheckPlugin start !!!");
		new Thread(new CheckOnline()).start();
		new Thread(new DbQueue()).start();
		return true;
	}

	public boolean stop() {
		logger.info("OnlineCheckPlugin stop !!!");
		return true;
	}
	
	public class DbQueue implements Runnable {
		@Override
		public void run() {
			while (true) {
				try {
					//logger.info("DbQueue run...");
					Thread.sleep(1000);
					boolean succeed = Db.tx(new IAtom() {
						public boolean run() throws SQLException {
							while (!GpsServer.dbQueue.isEmpty()) {
								try{
									Model<?> model = GpsServer.dbQueue.poll();
									if (model.get("id") == null){
										model.save();
									}else{
										model.update();
									}
								}catch(Exception e){
									logger.error(e.getMessage(), e);
								}
							}
							return true;
						}
					});

				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}

	public class CheckOnline implements Runnable {

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(GpsServer.CHECK_INTERVAL);

					/**
					 * 剔除超时不在线的车辆
					 */
					Iterator itr = GpsServer.onlineTerminals.keySet()
							.iterator();
					while (itr.hasNext()) {
						Object mdn = itr.next();
						Message msg = (Message)GpsServer.onlineTerminals.get(mdn).get(GpsServer.MO_MSG);
						long interval = System.currentTimeMillis()
								- msg.moTime.getTime();
						if (interval > GpsServer.TERMINAL_TIMEOUT) {
							//GpsServer.onlineTerminals.remove(mdn); 此句会导致异常ConcurrentModificationException
							itr.remove();
						}
					}

					/*
					 * 剔除超时的HttpSession
					 */
					Iterator itr2 = GpsServer.orgSessionMap.keySet().iterator();
					while (itr2.hasNext()) {
						Object key = itr2.next();
						List<HttpSession> list = GpsServer.orgSessionMap
								.get(key);
						for (int i = 0; i < list.size(); i++) {
							HttpSession session = list.get(i);
							try {
								long interval = System.currentTimeMillis() - session.getLastAccessedTime();
								if (interval > GpsServer.HTTPSESSION_TIMEOUT) {
									list.remove(i);
								}
							} catch (Exception e) {
								list.remove(i);
							}
						}
						GpsServer.orgSessionMap.put(key.toString(), list);
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

	}

}
